package com.gimi.cloud.bbp.commonService.sms;

import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gimi.cloud.bbp.common.utils.CommonUtil;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.dto.sys.AlidayuDTO;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;


public class AliDaYuSmsPortalImpl implements SmsPortal {
	
	private Logger logger = Logger.getLogger(AliDaYuSmsPortalImpl.class);

	@Override
	public String getSPName() {
		return "AliDaYu";
	}

	@SuppressWarnings("unchecked")
	@Override
	public String send(String phone, String content) {
		/*TripartiteAccount alisms = Global.getTripartiteAccount("ali_sms");
		String url = alisms.getUrl();//"https://eco.taobao.com/router/rest";
		String appkey = alisms.getAccount();//"23462385";
		String secret = alisms.getSecret();//"a334e9b83495506d881eb2a020058e18";

		Map<String, String> contentMap = JSONArray.parseObject(content,Map.class);

		String smsParam = JSONObject.toJSONString(contentMap.get("param"));

		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend("123456");
		req.setSmsType("normal");
		req.setSmsFreeSignName(Global.getString("web_name"));
		//req.setSmsParamString("{\"user\":\"abc123\",\"project\":\"project\",\"cou\":\"cou\",\"inv\":\"inv\"}");
		req.setSmsParamString(smsParam);
		req.setRecNum(phone);
		//req.setSmsTemplateCode("SMS_3090147");
		req.setSmsTemplateCode(contentMap.get("code"));
		AlibabaAliqinFcSmsNumSendResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
		if("0".equals(rsp.getResult().getErrCode())) {
			return "ok";
		} else {
			logger.error("短信发送结果Msg：" + rsp.getMsg());
			logger.error("短信发送结果Body：" + rsp.getBody());
			return "";
		}*/
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String sendNew(String phone,String noticeTypeNid) {
		//设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		//TODO 写死先
		String url = "http://gw.api.taobao.com/router/rest";//"https://eco.taobao.com/router/rest";
		String appkey = "23395868";//"23462385";
		String secret = "cc3a3fd7dddcc74d9472cbdebd5c8ffe";//"a334e9b83495506d881eb2a020058e18";
		String modelSms = noticeTypeNid;//"SMS_10990892"

		
		//初始化ascClient需要的几个参数
		final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		//替换成你的AK
		final String accessKeyId = appkey;//你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = secret;//你的accessKeySecret，参考本文档步骤2
		//初始化ascClient,暂时不支持多region
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
		accessKeySecret);
		try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		} catch (ClientException e1) {
			e1.printStackTrace();
		}
		IAcsClient acsClient = new DefaultAcsClient(profile);
		 //组装请求对象
		 SendSmsRequest request = new SendSmsRequest();
		 //使用post提交
		 request.setMethod(MethodType.POST);
		 //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		 request.setPhoneNumbers(phone);
		 //必填:短信签名-可在短信控制台中找到
		 request.setSignName("机蜜");
		 //必填:短信模板-可在短信控制台中找到
		 request.setTemplateCode(modelSms);
		 //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		 //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		 request.setTemplateParam("{\'code\':\'"+modelSms+"\',\'param\':{\'code\':\'${code}\'}}");
		 //可选-上行短信扩展码(无特殊需求用户请忽略此字段)
		 //request.setSmsUpExtendCode("90997");
		 //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		 //request.setOutId("yourOutId");
		//请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse = null;
		try {
			sendSmsResponse = acsClient.getAcsResponse(request);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			return "ok";
		}else{
			logger.error("短信发送结果Msg：" + sendSmsResponse.getMessage());
			logger.error("短信发送结果Body：" + sendSmsResponse.getRequestId());
			return "";
		}
	}
	/**
	 * 发送短信验证码
	 */
	public  String sendMessage(AlidayuDTO dto,String code,String noticeTypeNid){
		if(StringUtils.isAnyBlank(dto.getPhone()) || null == dto){//
			return "";
		}
		String url = "http://gw.api.taobao.com/router/rest";//dto.getUrl();
		String key = "23395868";//dto.getAccessKeyId();
		String secret = "cc3a3fd7dddcc74d9472cbdebd5c8ffe";//dto.getAccessKeySecret();
		String smsSignName ="给米钱包" ;//dto.getSign();
		String content = "{\"code\":\""+code+"\", \"product\":\"ufq\"}";//dto.getParams();
		TaobaoClient client = new DefaultTaobaoClient(url, key, secret);
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setSmsType("normal");
		req.setSmsFreeSignName(smsSignName);//短信签名，传入的短信签名必须是在阿里大于“管理中心-短信签名管理”中的可用签名。如“阿里大于”已在短信签名管理中通过审核，则可传入”阿里大于“（传参时去掉引号）作为短信签名。短信效果示例：【阿里大于】欢迎使用阿里大于服务。
		req.setSmsParamString(content);
		req.setRecNum(dto.getPhone());
		req.setSmsTemplateCode(noticeTypeNid);
		try {
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
			String res = String.valueOf(rsp.getBody());
			if(JsonUtil.isJSON(res)){
				JSONObject jsonObj = JSON.parseObject(res);//转化为json对象
				if(jsonObj.containsKey("alibaba_aliqin_fc_sms_num_send_response")){//发送成功
					jsonObj = jsonObj.getJSONObject("alibaba_aliqin_fc_sms_num_send_response").getJSONObject("result");
					if("true".equals(jsonObj.getString("success"))){
						return "ok";
					}
				}else if(jsonObj.containsKey("error_response")){//发送失败
					jsonObj = jsonObj.getJSONObject("error_response");
				}

			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return "";
	}

	@Override
	public Map<String, Integer> getUseInfo() {
		return null;
	}

}
